package com.metroinfo.workers;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import com.metroinfo.parser.GeneralSettings;

public class ChannelIO {

	protected SocketChannel sc;

	/*
	 * All of the inbound request data lives here until we determine that we've
	 * read everything, then we pass that data back to the caller.
	 */
	protected ByteBuffer requestBB;
	static private int requestBBSize = GeneralSettings.RECEIVE_DATA_SIZE;

	protected ChannelIO(SocketChannel sc, boolean blocking) throws IOException {
		this.sc = sc;
		sc.configureBlocking(blocking);
	}

	public static ChannelIO getInstance(SocketChannel sc, boolean blocking)
			throws IOException {
		ChannelIO cio = new ChannelIO(sc, blocking);
		cio.requestBB = ByteBuffer.allocate(requestBBSize);

		return cio;
	}

	public SocketChannel getSocketChannel() {
		return sc;
	}

	/*
	 * Resize (if necessary) the inbound data buffer, and then read more data
	 * into the read buffer.
	 */
	public int read() throws IOException {
		return sc.read(requestBB);
	}

	/*
	 * All data has been read, pass back the request in one buffer.
	 */
	public ByteBuffer getReadBuf() {
		return requestBB;
	}

	/*
	 * Start any connection shutdown processing. <P> This isn't really necessary
	 * for the insecure variant, but needed for the secure one where
	 * intermediate buffering must take place. <P> Return true if successful,
	 * and the data has been flushed.
	 */
	public boolean shutdown() throws IOException {
		return true;
	}

	/*
	 * Close the underlying connection.
	 */
	public void close() throws IOException {
		sc.close();
	}

	/*
	 * Write the src buffer into the socket channel.
	 */
	public int write(ByteBuffer src) throws IOException {
		return sc.write(src);
	}

    public boolean dataFlush() throws IOException {
    	return true; 
    }
}
